<?php

namespace Rjyst\ApiInvoke\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallCommand extends Command
{
    protected $signature = 'api-invoke:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst API Invoke package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst API Invoke 组件库...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst API Invoke 组件库吗？这将删除所有相关文件！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 恢复 API 路由文件
        $this->restoreApiRoutes();

        // 2. 删除创建的文件
        $this->deleteFiles();

        // 3. 恢复异常处理器
        $this->restoreExceptionHandler();

        // 4. 恢复内核文件
        $this->restoreKernel();

        // 5. 更新 composer.json
        $this->updateComposerAutoload();

        $this->info('🎉 RjYst API Invoke 组件库卸载完成！');
        $this->showUninstallInfo();
    }

    protected function restoreApiRoutes()
    {
        $this->info('恢复 API 路由文件...');

        $routeFile = base_path('routes/api.php');
        $defaultContent = "<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the \"api\" middleware group. Make something great!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request \$request) {
    return \$request->user();
});
";

        File::put($routeFile, $defaultContent);
        $this->info('✅ API 路由文件已恢复');
    }

    protected function deleteFiles()
    {
        $this->info('删除组件库创建的文件...');

        $filesToDelete = [
            app_path('Enums/Api/Response.php'),
            app_path('Factory/ParseException.php'),
            app_path('Http/Middleware/AcceptHeader.php'),
            app_path('Http/Controllers/Api/Controller.php'), // 修改路径
            app_path('helpers.php'),
        ];

        foreach ($filesToDelete as $file) {
            if (File::exists($file)) {
                File::delete($file);
                $this->info("✅ 删除文件: " . str_replace(base_path(), '', $file));
            } else {
                $this->line("⚠️  文件不存在: " . str_replace(base_path(), '', $file));
            }
        }

        // 删除空目录
        $dirsToDelete = [
            app_path('Enums/Api'),
            app_path('Enums'),
            app_path('Factory'),
            app_path('Http/Controllers/Api'), // 新增这个目录的清理
        ];

        foreach ($dirsToDelete as $dir) {
            if (File::isDirectory($dir) && count(File::allFiles($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->info("✅ 删除空目录: " . str_replace(base_path(), '', $dir));
            }
        }
    }

    protected function restoreExceptionHandler()
    {
        $this->info('恢复异常处理器...');

        $handlerFile = app_path('Exceptions/Handler.php');

        if (!File::exists($handlerFile)) {
            $this->line('⚠️  Handler.php 不存在');
            return;
        }

        $content = File::get($handlerFile);

        // 移除添加的 use 语句
        $useStatements = [
            'use App\Enums\Api\Response as CustomResponse;',
            'use App\Factory\ParseException;',
            'use Illuminate\Auth\Access\AuthorizationException;',
            'use Illuminate\Auth\AuthenticationException;',
            'use Illuminate\Database\Eloquent\ModelNotFoundException;',
            'use Illuminate\Support\Str;',
            'use Illuminate\Validation\ValidationException;',
            'use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;',
            'use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;'
        ];

        foreach ($useStatements as $useStatement) {
            $content = str_replace($useStatement . "\n", '', $content);
        }

        // 移除 render 方法（更精确的正则表达式）
        $content = preg_replace('/\n\s*public function render\(\$request, \$e\)\s*\{(?:[^{}]*|\{[^{}]*\})*\}/s', '', $content);

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($handlerFile, $content);
        $this->info('✅ 异常处理器已恢复');
    }

    protected function restoreKernel()
    {
        $this->info('恢复内核文件...');

        $kernelFile = app_path('Http/Kernel.php');

        if (!File::exists($kernelFile)) {
            $this->line('⚠️  Kernel.php 不存在');
            return;
        }

        $content = File::get($kernelFile);

        // 移除 AcceptHeader 中间件
        $content = str_replace(
            "            \\App\\Http\\Middleware\\AcceptHeader::class,\n",
            '',
            $content
        );

        // 恢复原始的 throttle 配置
        $content = str_replace(
            "'throttle:60,1',",
            "\\Illuminate\\Routing\\Middleware\\ThrottleRequests::class.':api',",
            $content
        );

        // 移除可能添加的 middlewareAliases（如果整个块都是我们添加的）
        $middlewareAliasesPattern = '/\n\s*\/\*\*\s*\n\s*\* The application\'s middleware aliases\.\s*\n.*?\*\/\s*\n\s*protected \$middlewareAliases = \[[^\]]*\];/s';
        $content = preg_replace($middlewareAliasesPattern, '', $content);

        File::put($kernelFile, $content);
        $this->info('✅ 内核文件已恢复');
    }

    protected function updateComposerAutoload()
    {
        $composerFile = base_path('composer.json');

        if (!File::exists($composerFile)) {
            return;
        }

        $composer = json_decode(File::get($composerFile), true);

        if (isset($composer['autoload']['files'])) {
            $helperPath = 'app/helpers.php';
            $composer['autoload']['files'] = array_filter($composer['autoload']['files'], function($file) use ($helperPath) {
                return $file !== $helperPath;
            });

            // 重置数组索引
            $composer['autoload']['files'] = array_values($composer['autoload']['files']);

            // 如果 files 数组为空，删除它
            if (empty($composer['autoload']['files'])) {
                unset($composer['autoload']['files']);
            }

            File::put($composerFile, json_encode($composer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            $this->info('✅ composer.json 自动加载配置已清理');
        }
    }

    protected function showUninstallInfo()
    {
        $this->line('');
        $this->line('<fg=green>✅ 卸载完成！已清理：</>');
        $this->line('• API 路由文件已恢复为默认状态');
        $this->line('• Response 枚举文件已删除');
        $this->line('• ParseException 工厂文件已删除');
        $this->line('• AcceptHeader 中间件文件已删除');
        $this->line('• helpers.php 助手函数文件已删除');
        $this->line('• Handler.php 中的自定义 render 方法已移除');
        $this->line('• Kernel.php 中的中间件配置已恢复');
        $this->line('• composer.json 自动加载配置已清理');
        $this->line('');
        $this->line('<fg=blue>🔧 建议执行：</>');
        $this->line('• 运行 <fg=green>composer dump-autoload</> 重新生成自动加载文件');
        $this->line('• 检查并清理可能的空目录');
        $this->line('');
        $this->line('<fg=yellow>⚠️  注意：</>');
        $this->line('• 如果你有自定义的 API 路由，请重新添加到 routes/api.php');
        $this->line('• Controller.php 基类文件保留（可能被其他代码使用）');
    }
}
